package com.dux.commons.scripts.java.impl.javacompiler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URI;


import com.sun.tools.javac.file.BaseFileObject;

/**
 * 加载容器类
 * @author 杜祥
 * @create 2013-6-17
 */
public class BinaryClass extends BaseFileObject
{
	/**
	 * class name
	 */
	private final String name;
	
	/**
	 * 将写入类数据
	 */
	private ByteArrayOutputStream output = new ByteArrayOutputStream();
	
	/**
	 * 
	 */
	private Class<?> definedClass;

	
	protected BinaryClass(String name) 
	{
		super(null);
		this.name = name;
	}

	
	/**
	 * {@link javax.tools.JavaFileObject.Kind#CLASS} 返回true
	 */
	@Override
	public boolean isNameCompatible(String simpleName, Kind kind) 
	{
		return Kind.CLASS.equals(kind);
	}

	/**
	 * 抛出{@link UnsupportedOperationException}
	 */
	@Override
	public URI toUri() 
	{
		throw new UnsupportedOperationException();
	}

	/**
	 * 创建新的ByteArrayInputStream包装类的二进制数据
	 * @return 返回新的ByteArrayInputStream
	 */
	@Override
	public InputStream openInputStream() throws IOException 
	{
		return new ByteArrayInputStream(output.toByteArray());
	}
	
	/**
	 * 打开ByteArrayOutputStream数据
	 * @return 字节输出流
	 */
	@Override
	public OutputStream openOutputStream() throws IOException
	{
		return output;
	}

	/**
	 * Throw {@link UnsupportedOperationException}
	 */
	@Override
	public CharSequence getCharContent(boolean ignoreEncodingErrors)throws IOException
	{
		throw new UnsupportedOperationException();
	}
	
	
	/**
	 * Throw {@link UnsupportedOperationException}
	 */
	@Override
	public Writer openWriter() throws IOException
	{
		throw new UnsupportedOperationException();
	}

	
	/**
	 * 不支持的操作
	 * return 0;
	 */
	@Override
	public long getLastModified() 
	{
		return 0;
	}

	
	/**
	 * 不支持的操作，返回false
	 * return false;
	 */
	@Override
	public boolean delete() 
	{
		return false;
	}

	
	@Override
	@Deprecated
	public String getName() 
	{
		return name + ".class";
	}

	/**
	 * 返回类名
	 */
	@Override
	protected String inferBinaryName(Iterable<? extends File> path)
	{
		return name;
	}

	
	/**
	 * 返回类的字节
	 * @return
	 */
	public byte[] getBytes()
	{
		return output.toByteArray();
	}
	

	/**
	 * 获得类已经加载的对象
	 * @return
	 */
	public Class<?> getDefinedClass()
	{
		return definedClass;
	}

	/**
	 * 设置类加载了这个对象
	 * @param definedClass
	 */
	public void setDefinedClass(Class<?> definedClass) 
	{
		this.definedClass = definedClass;
	}

	
	
}
